package com.cy.pj.common.aspect;

import com.cy.pj.common.annotation.RequiredCache;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
public class SysModuleCacheAspect {
    private Map<String, Map<String, Object>> cacheMap = new ConcurrentHashMap<>();
    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
    private void doCache(){}
    @Pointcut("@annotation(com.cy.pj.common.annotation.RequireCacheClear)")
    private void doClearCache(){}

    @Around("doCache()")
    public Object doCacheAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Get Data from cache");

        String cacheName = getCacheName(RequiredCache.class, joinPoint); //这里已经发送注解的class了，还需要在方法里判断注解吗
        Map<String, Object> cache = cacheMap.get(cacheName);
        if (cache == null) {
            cache = new ConcurrentHashMap<>();
            cacheMap.put(cacheName, cache);
        }

        Object result = cache.get("methodKey");
        if (result != null) {
            return result;
        }
        result = joinPoint.proceed();
        System.out.println("Put data to cache");
        cache.put("methodKey", result);
        return result;
    }

    @AfterReturning("doClearCache()")
    public void doAfterReturning() {
        //cache.clear();
    }

    private String getCacheName(Class<RequiredCache> requiredCacheClass, JoinPoint joinPoint) throws NoSuchMethodException {
        Class targetClass = joinPoint.getTarget().getClass();
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = targetClass.getMethod(ms.getName(), ms.getParameterTypes());

        Annotation annotation = targetMethod.getAnnotation(requiredCacheClass);
        String cacheName = null;

        return null;
    }
}
